var queryParameters = new Array();
var imgSrc = "";
var loopSearch = "";
var newPersonlist = [];
var personIds = [];
var targetTime = "null";
var oldCamera="";

// 摄像头数据
var cameralist = {
  camera1: "rtmp://192.168.0.101:1935/mytv/890",
  camera2: "rtmp://192.168.0.101:1935/mytv/892",
  camera3: "rtmp://192.168.0.101:1935/mytv/891"
};

// canvas配置
var canvas = document.getElementById("planCanvas");
var planContext = canvas.getContext("2d");

// 相似度滑动条
var elem = document.getElementById('js-range');
var init = new Powerange(elem, {
  min: 0,
  max: 100,
  start: 80,
  vertical: true,
  callback: displayValue
});
var similarityNum = 80;

var targetId = 0;


$(function(){

  // 播放视频
  initialise("camera1",cameralist.camera1);
  initialise("camera2",cameralist.camera2);
  initialise("camera3",cameralist.camera3);

  // 预览图片
  $(document).on("change","#uploadImg",function(){
    previewImage(this,"personImg");
  })

  //开始检索人脸
  $("[name='beginSearch']").click(function(){
    if($("#personImg").attr("default")=="true"){
      alert("请先选择图片");
    }
    else{
      // 设置canvas尺寸
      var planW = $(".plan-img").width(),
          planH = $(".plan-img").height();
      $("#planCanvas").attr({
        "width": planW,
        "height": planH
      });
      // 清空旧数据
      newPersonlist = [];
      personIds = [];
      planContext.clearRect(0, 0, planW, planH);
      $(".result-box>ul").empty();
      $(".plan-camera em").remove();
      targetTime = "null";
      oldCamera="";
      window.clearInterval(loopSearch);
      // 开始搜索
      getTargetId();
    }
  });

  // 鼠标经过人点显隐信息
  $(document).on("mouseenter",".plan-camera em",function(){
    var personId = $(this).attr("personid");
    var X = $(this).offset().left;
    var Y = $(this).offset().top;
    $.each(newPersonlist,function(index,object){
      if(object.id == personId){

        var similarity = (object.similarity*100).toFixed(0);
        var checkTime = moment(object.time).format("HH:mm");
        var numColor = "green";
        if(similarity<90) numColor="yellow";

        $(".plan-box").append(
          '<div class="person-tip animate zoomIn" style="top:'+Y+'px;left:'+X+'px">'+
            '<div class="check-img">'+
              '<img src="'+object.url+'" alt="" />'+
            '</div>'+
            '<div class="check-info">'+
              '<p>'+
                '<em class="'+numColor+'-one">'+similarity+'</em>'+
                '相似度：%'+
              '</p>'+
              '<span>Camera'+object.cameraId+'</span><br/>'+
              '<span>'+checkTime+'</span>'+
            '</div>'+
          '</div>'
        )
      }
    })
  })
  .on("mouseleave",".plan-camera em",function(){
    $(".person-tip").remove();
  });

  // 中屏点击摄像头icon显示画面
  $(document).on("click",".plan-camera input",function(){
    var cameraId = $(this).attr("cameraId");
    if($(".cameras-box").is(":hidden")){
      $(".middle-camera-box").empty().show().append(
        '<div id="middleCamera"></div>'+
        '<input type="button" class="closeCamera" value="关闭画面"/>'
      );
      initialise("middleCamera",cameralist[cameraId]);
    }
  })
  .on("click",".closeCamera",function(){
    $(".middle-camera-box").empty().hide();
  });

  // 放大图片
  $(document).on("click",".check-img",function(){
      var imgSrc = $(this).find("img").attr("src");
      $("body").append(
          '<div class="img-bigbox">' +
              '<img src="'+ imgSrc +'" />' +
          '</div>'
      );
  })
  .on("click",".img-bigbox",function(){
      $(".img-bigbox").animate({opacity:"0"},200,function(){
          $(".img-bigbox").remove();
      });
  });

  // 窗体发生变化
  window.onresize = function(){
    if($(".cameras-box").is(":visible")){
      $(".middle-camera-box").empty().hide();
    }
  };

})


// 相似度值
function displayValue() {
  similarityNum = parseInt(elem.value);
  console.log(similarityNum);
  document.getElementById('similarityValue').innerHTML = similarityNum;
}

// 获取目标id
function getTargetId(){
  $.ajax({
      type: "post",
      url: "http://192.168.0.101:8888/traffic-web/business/dispatched/searchCar",
      data: {
        image: imgSrc
      },
      dataType: "json",
      success: function(result){
        console.log(result);
        // code为200则有识别到人并开始布控
        if(result.code == 200){
          searchPerson();
          // // 每五秒查询一次
          loopSearch = setInterval(function(){
            searchPerson();
          },5000);
        }
        else{
          alert("图像中没有检测到人，请重新选择图片.");
        }
      }
  })
}


// 请求数据
function searchPerson(){
  var $tip = $(".result-box>p");
  var $list = $(".result-box>ul");

  $.ajax({
      type: "post",
      url: "http://192.168.0.101:8888/traffic-web/business/dispatched/getDispatched",
      data: {
        id: targetId
      },
      dataType: "json",
      success: function(result){
        console.log(result);
        // 没数据则不执行
        if(result.code == 100) return false

        targetId = result.id;
        var personlist = result.data;
        if($list.find("li").length == 0 && $tip.find(".checking").length=="0"){
          $tip.prepend('<span class="checking">搜索目标中...</span>');
        }

        if(personlist.length != 0){
          $.each(personlist,function(index,object){
            var similarity = (object.similarity*100).toFixed(0);
            var checkTime = moment(object.time).format("HH:mm");
            var numColor = "green";
            if(similarity<90) numColor="yellow";

            // 比对目标id是否一致
            // if(object.dispatchedId == targetId){

            // 比对相似度，如果大于指定相似度则绘制
            console.log(similarity,similarityNum);
            if(similarity>similarityNum){
              // 比对上一次出现的摄像头，如果不同则绘制
              if(object.cameraId != oldCamera){
                oldCamera = object.cameraId;
                // 插入人员信息
                $list.prepend(
                  '<li class="clearfix" id="personInfo'+object.id+'">'+
                    '<div class="check-left">'+
                      '<span>'+checkTime+'</span><br/>Camera'+object.cameraId+
                    '</div>'+
                    '<div class="check-right">'+
                      '<div class="check-img">'+
                        '<img src="'+object.url+'" alt="" />'+
                      '</div>'+
                      '<p>'+
                        '<em class="'+numColor+'-one">'+similarity+'</em>'+
                        '相似度：%'+
                      '</p>'+
                    '</div>'+
                  '</li>'
                );

                //往平面图中插入圆点
                $(".plan-camera"+object.cameraId).append(
                  '<em class="zoomIn '+numColor+'-one" personid="'+object.id+'"></em>'
                );

                //插入到目标数组用于显示详情
                newPersonlist.push(object);
                //插入id数组用于绘制线路
                personIds.push(object.id);

                var x0 = $(".plan-img").offset().left-3,
                    y0 = $(".plan-img").offset().top-3;
                var point2X = $("[personid='"+personIds[personIds.length-1]+"']").offset().left,
                    point2Y = $("[personid='"+personIds[personIds.length-1]+"']").offset().top;
                // 绘制其他点
                if(personIds[personIds.length-2] != undefined){
                  var point1X = $("[personid='"+personIds[personIds.length-2]+"']").offset().left,
                      point1Y = $("[personid='"+personIds[personIds.length-2]+"']").offset().top;
                  var x1 = point1X - x0,
                      y1 = point1Y - y0,
                      x2 = point2X - x0,
                      y2 = point2Y - y0;
                  // 绘制虚线
                  drawDashedLine(planContext,x1,y1,x2,y2,"rgba(255,87,69,0.6)","2",4);
                  // 绘制时间
                  planContext.font = "12px Courier New";
                  planContext.fillStyle = "red";
                  planContext.fillText(checkTime, (x2-18), (y2-10));
                }
                else {
                  // 绘制起始时间
                  var x1 = point2X - x0,
                      y1 = point2Y - y0;
                  planContext.font = "12px Courier New";
                  planContext.fillStyle = "red";
                  planContext.fillText(checkTime, (x1-18), (y1-10));
                }
              }
              // 如果相同则修改最新的一条记录
              else{
                // 更新结果列表的最后一条数据
                var $lastPerson = $("#personInfo"+personIds[personIds.length-1]);
                $lastPerson.find(".check-left").html('<span>'+checkTime+'</span><br/>Camera'+object.cameraId);
                $lastPerson.find(".check-img").find("img").attr("src",object.url);
                $lastPerson.find(".check-right").find("p").html(
                  '<em class="'+numColor+'-one">'+similarity+'</em>'+
                  '相似度：%'
                );
                $lastPerson.attr("id","personInfo"+object.id);
                //移除地图上的点并重新绘制
                $("[personid='"+personIds[personIds.length-1]+"']").remove();
                $(".plan-camera"+object.cameraId).append(
                  '<em class="zoomIn '+numColor+'-one" personid="'+object.id+'"></em>'
                );
                //插入数据到数组
                newPersonlist.push(object);
                personIds.push(object.id);
                // 撤销时间并重新描绘
                var x0 = $(".plan-img").offset().left-3,
                    y0 = $(".plan-img").offset().top-3;
                var point2X = $("[personid='"+personIds[personIds.length-1]+"']").offset().left,
                    point2Y = $("[personid='"+personIds[personIds.length-1]+"']").offset().top;
                var x1 = point2X - x0,
                    y1 = point2Y - y0;
                planContext.clearRect((x1-18), (y1-24),36,16);
                planContext.font = "12px Courier New";
                planContext.fillStyle = "red";
                planContext.fillText(checkTime, (x1-18), (y1-10));
              }
            }
            // }
          });
        }
      },
      error:function(result){
        console.log(result);
      }
  });
}


/**
    @params ctx 2D绘图环境
    @params sx 起始点X
    @params sy 起始点y
    @params tx 终点x
    @params ty 终点y
    @params color 线条颜色
    @params lineWidth 线条宽度
    @params dashLength 虚线间隔
**/
function drawDashedLine(ctx,sx,sy,tx,ty,color,lineWidth,dashLen){

    // 绘制虚线
    var len = cacuDis(sx,sy,tx,ty),
        lineWidth = lineWidth || 1,
        dashLen = dashLen || 5,
        num = ~~(len / dashLen);
    ctx.beginPath();
    for(var i=0;i<num;i++){
        var x = sx + (tx - sx) / num * i,
            y = sy + (ty - sy) / num * i;
        ctx[i & 1 ? "lineTo" : "moveTo"](x,y);
    }
    ctx.closePath();
    ctx.lineWidth = lineWidth;
    ctx.strokeStyle = color;
    ctx.stroke();
    ctx.save();

    // 绘制箭头
    ctx.translate(tx,ty);
    //我的箭头本垂直向下，算出直线偏离Y的角，然后旋转 ,rotate是顺时针旋转的，所以加个负号
    var ang=(tx-sx)/(ty-sy);
    ang=Math.atan(ang);
    if(ty-sy >= 0){
      ctx.rotate(-ang);
    }else{
      ctx.rotate(Math.PI-ang);//加个180度，反过来
    }
    ctx.lineTo(-5,-12);
    ctx.lineTo(5,-12);
    ctx.lineTo(0,-6);
    ctx.fillStyle="rgba(255,87,69,1)";
    ctx.fill(); //箭头是个封闭图形
    ctx.restore();
    ctx.save();
}
//计算两点之间的距离
function cacuDis(sx,sy,tx,ty){
    return Math.sqrt(Math.pow(tx-sx,2)+Math.pow(ty-sy,2));
}


/**
 * 视频播放
 * rtmpUrl  视频路径
 */
function initialise(boxid,rtmpUrl) {
    queryParameters['source'] = rtmpUrl;
    var soFlashVars = {
        src: queryParameters['source'],
        streamType: "live",
        autoPlay: "true",
        controlBarAutoHide: "true",
        controlBarPosition: "bottom",
        bufferTime: 0.8
    };
    var swfVersionStr = "11.1";
    var xiSwfUrlStr = "js/videoplayer/playerProductInstall.swf";
    var params = {
        quality: "high",
        bgcolor: "#000000",
        allowscriptaccess: "sameDomain",
        allowfullscreen: true
    };
    var attributes = {
        id: "StrobeMediaPlayback",
        name: "StrobeMediaPlayback",
        align: "middle"
    };
    swfobject.embedSWF("js/videoplayer/StrobeMediaPlayback.swf", boxid, "100%", "100%", swfVersionStr, xiSwfUrlStr, soFlashVars, params, attributes);
}


/** 生成图片预览图
 * file:  file控件
 * prvid: 图片预览容器
 */
function previewImage(file, prvid) {
    var tip = "只能选择jpg、png、gif格式的图片！"; // 设定提示信息
    var filters = {
        "jpeg"  : "/9j/4",
        "gif"   : "R0lGOD",
        "png"   : "iVBORw"
    };
    if (window.FileReader) {
        for (var i=0, f; f = file.files[i]; i++) {
            var fr = new FileReader();
            fr.onload = function(e) {
                var src = e.target.result;
                if (!validateImg(src)) {
                    console.log(tip)
                } else {
                  $("#"+prvid).attr({
                    "src": src,
                    default: false
                  });
                  imgSrc = src.split(",");
                  imgSrc = imgSrc[1];
                }
            };
            fr.readAsDataURL(f);
        }
    } else {
        if ( !/\.jpg$|\.png$|\.gif$/i.test(file.value) ) {
            alert(tip);
        } else {
            showPrvImg(file.value);
        }
    }
    function validateImg(data) {
        var pos = data.indexOf(",") + 1;
        for (var e in filters) {
            if (data.indexOf(filters[e]) === pos) {
                return e;
            }
        }
        return null;
    }
}
